import os
import os.path
import select
import sys
import subprocess
import settings
import os.path
from subprocess import Popen
from player import Player

currentPlaying = -1
player = Player()

def out(val):
	sys.stdout.write(val)
	sys.stdout.flush()

def outln(val):
	out(val + '\n')

def prompt():
	out(">")

def show_playlist(*args):
	filter = args[0] if len(args) > 0 else ''
	for key in settings.PLAY_LIST.iterkeys():
		name = settings.PLAY_LIST[key][1]
		path = os.path.dirname(settings.PLAY_LIST[key][0])
		if path.find(filter) > -1: 
			out("%d. %s [%s]\n" % (key, name, path))

def play(*args):
	global player, currentPlaying
	key = settings.PLAY_LIST.keys()[0]
	try:
		if len(args) > 0:
			key = int(args[0])
		filename = settings.PLAY_LIST[key][0]
		player.stop()
		player.play(filename)
		currentPlaying = key
		outln("%s - %d" % (player.last_message().strip('\n'), currentPlaying))
	except (KeyError, ValueError):
		outln("no such song in the list")
		

def stop(*args):
	global player
	global currentPlaying
	player.stop()
	currentPlaying = -1
def help(*args):
	for key in commands.iterkeys():
		print key

def deleteSong(*args):
	key = args[0] 
	if len(args) == 0:
		outln("specify song number") 
	try:
		key = int(args[0])
		filename = settings.PLAY_LIST[key][0]
		os.unlink(filename)
		del settings.PLAY_LIST[key]

	except (KeyError, ValueError):
		outln("no such song in the list")
	
def playNext():
	global player
	global currentPlaying
	if not player.is_playing() and currentPlaying > -1:
		outln("")
		play(selectNextSong())
		prompt()

def forcePlayPrev():
	global currentPlaying
	global player
	keys = settings.PLAY_LIST.keys()
	prev = keys[len(keys) - 1]
	for key in keys:
		if key == currentPlaying:
			break
		prev = key
	player.stop()
	play(prev)	


	

def forcePlayNext():
	global player
	player.stop()
	play(selectNextSong())

def parseArgs(cmd):
	toks = cmd.split(' ')
	return toks[0], toks[1:]

def processCmd(cmd):
        cmd, args = parseArgs(cmd)
	if cmd in ("exit", 'quit'):
		stop()
		return False
	if cmd in commands:
		commands[cmd](*args)
	else:
		outln("Unknown command")
	prompt()
	return True

def selectNextSong():
	keys = sorted(settings.PLAY_LIST.iterkeys())
	keyMin = keys[0]
	keyMax = keys[len(keys)-1]
	for next in range(currentPlaying + 1, keyMax + 1):
		if next in settings.PLAY_LIST:
			return next
	return keyMin 


def build_playlist(root):
	i = 0
	for dirbase, dirs,files in os.walk(root):
		for file in files:
			ext = os.path.splitext(file)[1]
			if ext in settings.SOUND_FILES:
				settings.PLAY_LIST[i] = (os.path.abspath(os.path.join(dirbase, file)), file)
			i += 1

commands = {'ls':show_playlist
	    ,'p':play
	    ,'s':stop
	    ,'h':help
            ,'d':deleteSong
	    ,'next':forcePlayNext
	    ,'prev':forcePlayPrev

}
def main():
	poll = select.poll()
	poll.register(sys.stdin.fileno(), select.POLLIN)
	running = True
	prompt()
	while running:
		events = poll.poll(500)
		for fileno, event in events:
			if fileno == sys.stdin.fileno():
				#print "begin read "#, os.fstat( fileno ).st_size, sys.stdin.tell()
				cmd = ""
				data = ""
				while data != '\n':
					data = sys.stdin.read(1)
					cmd += data
				cmd = cmd.strip()
				running = processCmd(cmd)
		playNext()

if __name__== '__main__':
	folder = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
	build_playlist(folder)
	main()
